<template>
  <div>
    <div class="vm-manage-search">
      <el-input
        v-model="keyword"
        placeholder="请输入搜索内容"
        clearable
        @input="getComputeByVpcData"
      />
    </div>
    <div
      class="vm-manage-table content-wrapper el-card el-card__body is-always-shadow virtual-network-common"
    >
      <TableComponent
        ref="tableRef"
        :table-list="state.tableData"
        :table-column-info="computeNodeByVpc"
        :button-slot="true"
        :selection="true"
        :options-width="220"
        @updateData="setPageInfo"
        @defaultPageData="setDefaultPage"
        @rowDblclick="handleRowDblclick"
      >
        <template #CreatedAt="{ data: { CreatedAt } }">
          <span v-text="dateFormat(CreatedAt)" />
        </template>
        <template #option="{ data }">
          <div
            class="flex items-center justify-center space-x-3 sm:(space-x-1)"
          >
            <template v-for="item in getButton(data)" :key="item.name">
              <el-link
                :type="item.type"
                size="small"
                :underline="false"
                v-text="item.name"
                @click="item.click(data, item.clickType)"
              />
            </template>
          </div>
        </template>
      </TableComponent>
    </div>
  </div>
</template>
<script setup>
import { onMounted, onUnmounted, ref, shallowReactive, watch } from 'vue';
import TableComponent from '@/components/table/TableComponent.vue';
import debounce from 'lodash/debounce';
import { useRouter } from 'vue-router';
import { computeNodeByVpc } from '@/views/simulation/defaultConfig';
import { dateFormat, xtend } from '@/utils/common';
import { instanceToPlain } from 'class-transformer';
import {
  batchOptionByVPCApi,
  delVPCBatchApi,
  generateVPCApi,
  getVPCListByComputedApi,
} from '@/api/topo/simulationApi/vpc';
import { ElMessage, ElMessageBox } from 'element-plus';
import { emitter } from '@/utils/bus';
import { allCount } from '@/layout/notification/service/service';
import { useOperateStatus } from '@/pinia/modules/operateStatus';
import {
  useMouseMoveByTree,
  handleTableRowDblClick,
} from '@/hooks/useMouseMoveByTree';
let useOperate = useOperateStatus();

const router = useRouter();
const tableRef = ref(null);
const pageInfo = ref(null);
const keyword = ref('');
const state = shallowReactive({
  tableData: [],
});

const vpcID = ref('');

// 节点数据
const props = defineProps({
  node: null,
  treeRef: null,
});

const {
  _nodeLevel,
  _nodeName,
  currentNode,
  _expandArr,
  _type,
  tagStatus,
  treeRefMove,
} = useMouseMoveByTree();

const taskFunc = data => {
  const { msg } = data;
  const info = msg.update || msg.create;
  allCount.value = msg.count;

  // 判断是虚拟机当前页面操作且完成或者失败的操作
  if ((info.status === 2 || info.status === 3) && vpcID.value) {
    getComputeByVpcData();
  }
};
// 监听websocket消息通知
emitter.on('Task', taskFunc);

/**
 * 获取计算节点-VPC（防抖）
 * @type {DebouncedFuncLeading<(function(): Promise<void>)|*> | DebouncedFunc<(function(): Promise<void>)|*>}
 */
const getComputeByVpcData = debounce(async () => {
  const searchInfo_ = xtend(instanceToPlain(pageInfo.value), {
    keyword: keyword.value,
  });

  const computedId = props.node?.id.substring(2);
  return getVPCListByComputedApi(computedId, searchInfo_).then(res => {
    if (!(res instanceof Error)) {
      const {
        data: { list, total, page, pageSize },
      } = res;
      tableRef.value?.setPageInfo({ total, page, pageSize });
      state.tableData = list;
    }
  });
}, import.meta.env.VITE_INPUT_DEBOUNCE_TIME);

// 初始化页数
const setDefaultPage = arg => (pageInfo.value = arg);

const setPageInfo = arg => {
  pageInfo.value = arg;
  getComputeByVpcData();
};

/**
 * VPC操作枚举、并定义点击事件
 * @param arg
 */
const getButton = arg => {
  let statusStr = !arg.generate ? '0' : arg.status ? '1' : '2';
  const map = {
    0: {
      name: '生成',
      clickType: 'generate',
      primary: 'success',
    },
    1: {
      name: '停止',
      clickType: 'stop',
      primary: 'danger',
    },
    2: {
      name: '启动',
      clickType: 'start',
      primary: 'primary',
    },
  };
  const button = {
    link: true,
    name: map[statusStr].name,
    clickType: map[statusStr].clickType,
    type: map[statusStr].primary,
    click: (arg, type) => stateVpc(arg, type),
  };
  return [button, ...baseButton];
};

const stateVpc = (item, type) => {
  if (type === 'generate') {
    generateVPCApi(item.ID).then(res => {
      if (!(res instanceof Error)) {
        ElMessage.success(`${res.msg}`);

        if (res.data?.taskID) {
          useOperate.setOperateStatus('vpc', {
            id: res.data.taskID,
            type,
            listItem: item,
          });
        }
      }
    });
  } else {
    batchOptionByVPCApi({
      operation: type,
      ids: [item.ID],
    }).then(res => {
      if (!(res instanceof Error)) {
        ElMessage.success(`${res.msg}`);

        if (res.data?.taskID) {
          useOperate.setOperateStatus('vpc', {
            id: res.data.taskID,
            type,
            listItem: item,
          });
        }
      }
    });
  }
};

const baseButton = [
  {
    link: true,
    type: 'warning',
    name: '编辑',
    click: item => {
      emitter.emit('addOrEditVPC_bus', item);
    },
  },
  {
    link: true,
    type: 'danger',
    name: '删除',
    click: item => {
      ElMessageBox.confirm(
        `删除VPC 【${item.name}】 ，删除后将不可恢复！`,
        '删除VPC',
        {
          confirmButtonText: '删 除',
          cancelButtonText: '取 消',
          type: 'warning',
          center: true,
          customClass: 'delMessageBox',
          confirmButtonClass: 'delButtonClass',
        },
      ).then(async () => {
        delVPCBatchApi({
          ids: [item.ID],
        }).then(res => {
          if (!(res instanceof Error)) {
            ElMessage.success(`删除成功!`);
            if (item.generate) {
              useOperate.setOperateStatus('vpc', {
                id: res.data.taskID,
                type: 'delete',
                listItem: item,
              });
            } else {
              getComputeByVpcData();

              let node = props.treeRef?.getNode('v-' + item.ID);
              props.treeRef?.remove(node);
            }
          }
        });
      });
    },
  },
];

emitter.on('vpcUpdateData', getComputeByVpcData);

// 监听传递过来的节点数据
watch(
  () => props.node,
  val => {
    vpcID.value = props.node?.id ? props.node.id.substring(2) : null;

    if (vpcID.value) {
      getComputeByVpcData();
    }
  },
  { immediate: true },
);

const handleRowDblclick = arg => {
  handleTableRowDblClick({
    arg,
    type: 'vpc',
    idKey: 'ID',
    expandKey: 'computerID',
    sessionKey: 'vpc',
    _nodeLevel,
    _nodeName,
    currentNode,
    _expandArr,
    _type,
    treeRefMove,
    tagStatus,
  });
};

/**
 * 挂载-生命周期
 */
onMounted(() => {});

/**
 * 卸载-生命周期（主要处理清除定时器、解绑操作）
 */
onUnmounted(() => {
  emitter.off('vpcUpdateData', getComputeByVpcData);
  emitter.off('Task', taskFunc);
});
</script>
<style lang="scss" scoped></style>
